package com.yupi.springbootinit.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.mapper.SysteminfoMapper;
import com.yupi.springbootinit.model.entity.Systeminfo;

import javax.annotation.Resource;
import java.util.Random;

public class SMSUtils {

    private static final String ACCESS_KEY_ID = "LTAI5tCCZ6qG63GhZq54qhs3";//AccessKey自己账号的
    private static final String ACCESS_KEY_SECRET = "jG1B1GhkP5MLxPXEZW05zQ4Ah9xsQN";
    private static final String ENDPOINT = "dysmsapi.aliyuncs.com";//固定死
    private static final String SIGNNAME = "红薯科技";//签名名称
    private static final String TCODE = "SMS_478610390";//模版的编号


    public static String sendSms(String phoneNumbers) throws Exception {

        String code = generateVerificationCode();
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(ACCESS_KEY_ID)
                // 您的AccessKey Secret
                .setAccessKeySecret(ACCESS_KEY_SECRET);
// 访问的域名
        config.endpoint = ENDPOINT;
        Client client = new Client(config);
        if (client == null || phoneNumbers == null) {
            throw new NullPointerException("Client or phoneNumbers is null");
        }
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phoneNumbers)
                .setSignName(SIGNNAME)
                .setTemplateCode(TCODE)
                //此处是设计模版的时候预留的变量${code}就验证码，用下面的随机生成4位数字传入
                .setTemplateParam(String.format("{\"code\":\"%s\"}", code));

        SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
        if (sendSmsResponse == null) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "发送短信失败");
        }
        if(!sendSmsResponse.getBody().code.equals("OK")){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "发送短信失败");
        }
        // 发送短信成功，此处可以更新数据库记录的发送短信次数
        // 注意：此处仅为示例，实际使用时请根据您的业务逻辑进行相应的数据库操作
        // 更新数据库记录的发送短信次数

        return code;

    }


    /**
     * 验证码随机四位
     */
    private static String generateVerificationCode() {
        // 生成四位数字验证码
        Random random = new Random();
        int code = random.nextInt(10000); // 随机生成 0 到 9999 的整数
        return String.format("%04d", code); // 保证生成的是四位数字，不足四位时前面补0
    }
}
